<!-- 打开与保存后台drw文件 -->
<template>
  <div>
      <el-dialog   :modelValue="dialogVisible"  title="文件"  width="40%"
                  :close-on-click-modal="false" :close-on-press-escape="false"
                  :show-close="false" >

                  <div  style="display: flex; flex-direction: row; width: 100%; " >
                      <el-tree  ref="dir" :data="listDir" 
                          class="clsTree"
                          :props="defaultProps" 
                          node-key="path" 
                          :current-node-key="currentobj"  
                          highlight-current  
                          :default-expanded-keys="defaultobj"
                          @node-click="changeDir"
                          ></el-tree>
                      <el-tree  ref="file" :data="listFile" 
                          class="clsTree"
                          :props="defaultProps" 
                          node-key="label"  
                          highlight-current 
                          :default-expanded-keys="defaultobjfile"
                          @node-click="changeFile"
                          default-expand-all>
                      </el-tree>

                  </div>

                  <div  style="display: flex; flex-direction: row; width: 100%; margin-top: 20px;" >
                    <el-dropdown style="width: 100px;"   @command="handleDirFunc" >
                      <span>
                        目录操作
                        <el-icon><ArrowDownBold /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="adddir">增加</el-dropdown-item>
                          <el-dropdown-item command="deldir" >删除</el-dropdown-item>
                          <el-dropdown-item command="renamedir" >重命名</el-dropdown-item>
                          <el-dropdown-item command="freshdir" >刷新目录</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>

                    <el-dropdown style="width: 100px;"   @command="handleFileFunc" >
                      <span>
                        文件操作
                        <el-icon><ArrowDownBold /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="delfile" >删除</el-dropdown-item>
                          <el-dropdown-item command="renamefile" >重命名</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>

                    <span v-if="configNewFile" style="width: 200px;" >新文件名：</span>
                    <el-input v-if="configNewFile"  v-model="newFileName" ></el-input>
                </div>



        <template #footer>
          
          <!-- <el-button @click="handleTest">测试</el-button> -->
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleOk">确 定</el-button>
        </template>
      </el-dialog>

  </div>
</template>

<script>

import {ElMessage, ElMessageBox} from "element-plus"
import { mapState } from 'vuex'
import request from "@/utils/drawutils/request";
import {ArrowDownBold} from "@element-plus/icons-vue";
import { nextTick } from "vue";

export default {
  name: "DlgBackDrwFile",
  props:{ dialogVisible: Boolean, configNewFile: Boolean },
  components:{ArrowDownBold},
  emits:[ "resFile" ],

  computed: mapState([
        'projectid',
        'projectExist'
    ]),

  mounted() {
    // console.log( "projectid: ",  this.$route.query.projectid )
    // if( this.$route.query.projectid )
    //     this.$store.commit('setProjectId',  this.$route.query.projectid )  

    setTimeout(() => {
        // 这里是你想要延时执行的代码
        if( this.projectExist ){
          this.freshDir(  )
        }
    }, 1000);
  },
  
  data(){
    return{
      listDir: [],
      listFile: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentobj: "",
      nodekey: "path",
      defaultobj: [],
      defaultobjfile: [],
      newFileName:  "",

    }
  },
  watch: {

  },
  methods:{
    //获取目录
    getDir(  path, projectid  ){
      // console.log( "getDir" )
      request.post("/dirfilem/getdir", {dir: path, projectid: projectid }).then(res => {
        // console.log( res )
        if( res.code === "1" ){
          this.listDir = []
          res.data.label = "后台根目录 /"
          this.listDir.push(  res.data )
          // console.log( "dir array",  this.listDir )

        }
      })
    },

    //获取文件
    async  getFile(  path, projectid  ){

      const res = await request.post("/dirfilem/getfile", {dir: path, projectid: projectid })
      // console.log( "files", res )
      if( res.code === "1" ){
          this.listFile = []
          this.listFile = res.data 
          
          // console.log( "listFile", this.listFile )

          // console.log( this.listFile )
      }

    },

    //保存文件
    handleOk(  ){
      if( this.configNewFile )
        this.saveFile(  )
      else
        this.loadFile(  )
       
    },

    loadFile(  ){
        //获取当前节点的信息
      const nodedir = this.$refs.dir.getCurrentNode();
      const nodefile = this.$refs.file.getCurrentNode();

      // console.log( nodedir, nodefile )
      if(  !nodedir || !nodefile ){
        ElMessage({ type: 'error',  message: "请选择要打开的文件!" })
        return
      }

      let obj = { savedir: nodedir.path, filename: nodefile.label }
      // console.log( obj )
      this.$emit( "resFile", 1, obj )
    },

    saveFile(  ){
      const nodedir = this.$refs.dir.getCurrentNode();
      if(  !nodedir  ){
        ElMessage({ type: 'error',  message: "请选择要保存的目标目录!" })
        return
      }
      if(  this.newFileName.trim() === ""  ){
        ElMessage({ type: 'error',  message: "请输入文件名称!" })
        return
      }

      if( this.newFileName.slice(-3) != "drw" ){
        this.newFileName = this.newFileName + ".wdrw"
      }

      let obj = { savedir: nodedir.path, filename: this.newFileName }
      // console.log( obj )
      this.$emit( "resFile", 1, obj )
    },

    handleCancel(  ){
      this.$emit( "resFile", 0 )
    },

    handleTest(  ){
      //设置当前节点
      // this.currentobj = "333"
      // this.$refs.dir.setCurrentKey(this.currentobj);
      // console.log(  this.currentobj )

      //获取当前节点的信息
      const currentNode = this.$refs.dir.getCurrentNode();
      if (currentNode) {
        const currentNodeData = currentNode.data;
        // console.log('当前节点信息:', currentNode);
      } else {
        // console.log('没有当前节点');
      }

    },
    changeDir( data, node, component ){
      // console.log( data )
      this.getFile( data.path, this.projectid )
    },

    freshCurrentDir(  ){
      const nodedir = this.$refs.dir.getCurrentNode();

      this.getFile( nodedir.path, this.projectid )
    },

    //目录操作功能
    handleDirFunc( command ){
      // console.log( command )
      if( command === "freshdir" ){
        this.freshDir(  )

      }

      if( command === "adddir" ){
        const nodedir = this.$refs.dir.getCurrentNode();
        if( nodedir === null ){
          ElMessage({ type: 'error',  message: "请选择创建的父目录!" })
          return
        }

        ElMessageBox.prompt('请输入子目录名称', '子目录名称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:  "新目录",
        })
        .then(({ value }) => {
            let obj = {  parent: nodedir.path, subdir: value, projectid: this.projectid  }
            request.post("/dirfilem/makedir",  obj ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "创建成功" })
                this.defaultobj = []
                if( nodedir.path === "/" )
                  this.defaultobj.push( '/' + value )
                else
                  this.defaultobj.push( nodedir.path + '/' + value )

                // console.log( "add dir ",nodedir.path + '/' + value )
                this.getDir("/", this.projectid )
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {
        })

      }

      if( command === "deldir" ){
        const nodedir = this.$refs.dir.getCurrentNode();
        ElMessageBox.confirm(
          '是否删除文件夹' + nodedir.label + '?',
          '警告',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
        )
        .then(() => {
          let obj = { dir: nodedir.path, projectid: this.projectid }
          
          let index = nodedir.path.lastIndexOf('/');
          let parentdir = "/"
          if( index == 0 )
            parentdir = "/"
          else
            parentdir = nodedir.path.substring(0, index)
          // console.log( "del dir:", nodedir.path, parentdir )

          this.defaultobj = []
          this.defaultobj.push( parentdir )

          request.post("/dirfilem/deldir", obj  ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "删除成功" })
                this.getDir("/", this.projectid)
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {
        })
        
      }

      if( command === "renamedir" ){
        const nodedir = this.$refs.dir.getCurrentNode();
        if( nodedir === null ){
          ElMessage({ type: 'error',  message: "请选择目录节点!" })
          return
        }

        ElMessageBox.prompt('请输入新子目录名称', '子目录名称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue:  nodedir.label,
        })
        .then(({ value }) => {
            let obj = {  oldpath: nodedir.path, newdirname: value , projectid: this.projectid }
            request.post("/dirfilem/renamedir",  obj ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "更名成功" })
                
                //自动选中更新目录
                const lastIndex = nodedir.path.lastIndexOf('/');
                const beforeLastSlash = nodedir.path.substring(0, lastIndex);
                this.defaultobj = []
                this.defaultobj.push( beforeLastSlash + '/' + value )
                this.getDir("/", this.projectid)
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {

        })
        
      } // end if

    },

    handleFileFunc( command ){
      const nodedir = this.$refs.dir.getCurrentNode();
      const nodefile = this.$refs.file.getCurrentNode();

      // console.log( nodedir, nodefile )
      if(  !nodedir || !nodefile ){
        ElMessage({ type: 'error',  message: "请选择要操作的文件!" })
        return
      }

      if( command === "delfile" ){

        ElMessageBox.confirm(
          '是否删除文件' + nodefile.label + '?',
          '警告',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
        )
        .then(() => {
          let obj = { dir: nodedir.path, file: nodefile.label, projectid: this.projectid }
          request.post("/dirfilem/delfile", obj  ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "删除成功" })
                this.getFile(nodedir.path, this.projectid ).then(data => {
                  if( this.listFile.length > 0 ){
                    this.defaultobjfile[0] =  this.listFile[0].label 
                    // console.log( "this.defaultobjfile", this.defaultobjfile )
                    // console.log(  "new " , this.listFile[0].label )
                    this.$refs.file.setCurrentKey( this.listFile[0].label  )
                  }
                })
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {
        })
        
      }  // end if 

      //文件更名
      if( command === "renamefile" ){
        ElMessageBox.prompt('请输入新文件名称', '子目录名称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue:  nodefile.label,
        })
        .then(({ value }) => {
            let obj = {  path: nodedir.path, oldfile : nodefile.label , newfile: value, projectid: this.projectid }
            request.post("/dirfilem/renamefile",  obj ).then(res => {
              // console.log( res )
              if( res.code === "1" ){
                ElMessage({ type: 'success',  message: "更名成功" })
                this.getFile( nodedir.path, this.projectid )
              }
              else{
                ElMessage({ type: 'error',  message: res.msg })
              }
            })
        })
        .catch(() => {

        })
        
      } // end if

    },  // end handleFileFunc

    changeFile( data, node, component ){
      this.newFileName = node.label      
    },

    freshDir(  ){
        this.defaultobj = []
        this.defaultobj.push( '/' )
        this.getDir( "/", this.projectid )
        this.getFile( "/", this.projectid )
    },
    
    freshEmptyDir(  ){
      if( this.listDir.length == 0 )
        this.freshDir(  )
    },

  },  // end of methods

}

</script>

<style  lang="less" scoped >

.clsTree{
  border: 1px solid black;  
  flex: 1; 
  height: 50vh; 
  overflow-y: auto;
}

::v-deep( .el-tree .el-tree-node.is-current > .el-tree-node__content ){
          background-color: rgb(121, 235, 201); /* 选择你想要的颜色 */
}

</style>